package com.n.passwordbook.LaunchWindow;

import com.n.passwordbook.MainWindow.MainWindow;
import com.n.passwordbook.PasswordBook.PasswordBook;
import com.n.passwordbook.Utils.CryptographyHelper;
import com.n.passwordbook.Utils.Helper;
import com.n.passwordbook.Utils.Settings;
import com.n.passwordbook.Utils.WindowHelper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class ImportPage implements Initializable
{
    public Text txt_passwordWrong;
    @FXML
    public TextField tb_path;
    @FXML
    public PasswordField pb_password;

    public void hlBrowseFileImport(ActionEvent e)
    {
        File passwordBookFile = Helper.selectPasswordBookFile("选择需要导入的文件");
        if (passwordBookFile == null)
        {
            return;
        }
        tb_path.setText(passwordBookFile.getPath());
    }

    public void hlOkCheckPassword(ActionEvent e)
    {
        if (!pb_password.getText().equals(""))//密码不为空
        {
            if (PasswordBook.checkIfPasswordBookPathValid(new File(tb_path.getText()), pb_password.getText()))
            {
                try
                {
                    CryptographyHelper.setPBKey(pb_password.getText());
                    PasswordBook.setPasswordBook(pb_password.getText(), tb_path.getText());
                    Settings.setPasswordBookPath(new File(tb_path.getText()));
                    Settings.saveSettingsFile();
                    pb_password.setText("");
                    TmpDataHelper.MainWindowPreloadThread.join();
                    WindowHelper.changeMainSceneRootWithFadeOutAndFadeIn(TmpDataHelper.MainWindowLoader,
                            MainWindow::initializeControllerManually,TmpDataHelper.MainWindowRoot);
                }
                catch (IOException ioException)
                {
                    ioException.printStackTrace();
                    txt_passwordWrong.setOpacity(1);
                }
                catch (InterruptedException ex)
                {
                    ex.printStackTrace();
                }
            }
            else
            {
                txt_passwordWrong.setOpacity(1);
            }
        }
        else
        {
            txt_passwordWrong.setOpacity(1);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle)
    {
        txt_passwordWrong.setOpacity(0);
    }
}
